package com.fafu.rbac.security.controller;

import com.fafu.common.redis.utils.ByteRedisUtil;
import com.fafu.common.web.bean.Result;
import com.fafu.common.web.bean.ResultUtil;
import com.fafu.rbac.domain.entity.User;
import com.fafu.rbac.security.bean.WegoUserDetails;
import com.fafu.rbac.security.utils.JwtUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class LoginController {
    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private ByteRedisUtil<WegoUserDetails> wegoUserDetailsByteRedisUtil;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        UsernamePasswordAuthenticationToken passwordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(passwordAuthenticationToken);
        if(authenticate == null){
            return ResultUtil.error(401,"error");
        }
        WegoUserDetails userDetails = (WegoUserDetails) authenticate.getPrincipal();

        user = userDetails.getUser();
        //token中直接保存用户id
        String token = jwtUtil.generateToken(user.getId());

        //将完整的用户信息缓存到Redis中
        wegoUserDetailsByteRedisUtil.set("user:"+user.getId(),userDetails);


        return ResultUtil.success().addData("token",token);
    }
}
